package kr.hkit.powerjava.chapter23;

class Counter{
	private int value;
	public  synchronized void increment(){value++;}
	public  synchronized void decrement(){value--;}
	public  synchronized void prnCounter(){System.out.println(value);	}
}
class SharedThread extends Thread{
	Counter shareCounter;
	

	public SharedThread(Counter shareCounter) {
		this.shareCounter = shareCounter;
		start();
	}
	@Override
	public void run() {
		int i = 0;
		while(i<20000){
			shareCounter.increment(); //counter의 value값을 증가
			shareCounter.decrement();
			
			if(i % 40 == 0)
				shareCounter.prnCounter();
			
			try{
				sleep((int)(Math.random()*10));
			}catch(InterruptedException e){}
			i++;
			
		}
		
	}
}
public class CounterTest {
	public static void main(String[] args) {
		Counter c = new Counter();
		
		new SharedThread(c);
		new SharedThread(c);
		new SharedThread(c);
		new SharedThread(c);
	}
}
